﻿using PlaneClean.Models;
using PlaneCleanEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DbFactory;
using static System.Net.WebRequestMethods;
using System.Web.Http;
using PlaneClean.Filter;
using SqlSugar;
using PlaneClean.ViewModels;
using PlaneClean.CommonHelp;

namespace PlaneClean.Controllers.ManagerController
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class UserController : ManagerController
    {

        /// <summary>
        /// 查询用户列表 //要获取axios params的参数 就在 方法再添加对应的参数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ListResponse<t_user> List(PageListRequest<t_user> request)
        {
            if (request.pageIndex <= 0) request.pageIndex = 1;
            if (request.pageSize <= 0) request.pageSize = 100;
            int total = 0;
            ListResponse<t_user> response = new ListResponse<t_user>();
            response.bodyList = new List<t_user>();
            response.result = "NG";

            var Sugar = DbFactory.dbFactory.Db.Queryable<t_user>();
            //加快了分页查询的速度（SELECT Count(*) FROM `t_user`  WHERE ( `u_id` > @u_id0 ) ）使用where 后查询Count(*)速度会大幅度提升
            Sugar.Where(a => a.u_id > 0 && a.u_state >= 0);
            if (request.body.u_id > 0)
            {
                Sugar = Sugar.Where(a => a.u_id == request.body.u_id);
            }
            if (!string.IsNullOrEmpty(request.body.u_name))
            {
                Sugar = Sugar.Where(a => a.u_name == request.body.u_name);
            }
            if (!string.IsNullOrEmpty(request.body.u_phone))
            {
                Sugar = Sugar.Where(a => a.u_phone == request.body.u_phone);
            }
            if (request.body.u_state != null)
            {
                Sugar = Sugar.Where(a => a.u_state == request.body.u_state);
            }
            if (!string.IsNullOrEmpty(request.body.u_nick))
            {
                Sugar = Sugar.Where(a => a.u_nick == request.body.u_nick);
            }
            if (!string.IsNullOrEmpty(request.orderColumn))
            {
                string order = request.orderColumn;
                if (!string.IsNullOrEmpty(request.orderSort))
                {
                    if (request.orderSort == "ascending")
                    {
                        request.orderSort = "asc";
                    }
                    if (request.orderSort == "descending")
                    {
                        request.orderSort = "desc";
                    }
                    order = order + " " + request.orderSort;
                }
                Sugar.OrderBy(order);
            }

            List<t_user> planeList = Sugar.OrderBy(a => a.u_id, OrderByType.Asc).ToPageList(request.pageIndex, request.pageSize, ref total);
            response.bodyList.AddRange(planeList);
            response.total = total;

            response.result = "OK";
            return response;
        }
 
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse Add(BaseRequest<t_user> request)
        {
            BaseResponse response = new BaseResponse();
            //if (request.body == null)
            //{
            //    response.reason = "请求body不能为空";
            //    return response;
            //}
            if (request.body.u_id > 0)
            {
                response.reason = "有主键请调用更新接口";
                return response;
            }
            List<t_user> userList = DbFactory.dbFactory.Db.Queryable<t_user>().Where(a => a.u_name == request.body.u_name || a.u_phone == request.body.u_phone).ToList();
            if (userList.Where(a => a.u_name == request.body.u_name).ToList().Count > 0)
            {
                response.reason = "用户名已存在,新增失败";
                return response;
            }
            if (userList.Where(a => a.u_phone == request.body.u_phone).ToList().Count > 0)
            {
                response.reason = "手机号已存在,新增失败";
                return response;
            }
            if(request.body.u_state == null)
            {
                request.body.u_state = 1;
            }
            request.body.u_create_time = DateTime.Now;
            int pId = DbFactory.dbFactory.Db.Insertable(request.body).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnIdentity();
            if (pId <= 0)
            {
                response.reason = "插入数据库异常,新增失败";
                return response;
            }
            response.result = "OK";
            return response;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse Update(BaseRequest<t_user> request)
        {
            BaseResponse response = new BaseResponse();
            if (request.body.u_id <= 0)
            {
                response.reason = "没有主键请调用新增接口";
                return response;
            }
            t_user plane = DbFactory.dbFactory.Db.Queryable<t_user>().First(a => a.u_id == request.body.u_id);
            if (plane == null)
            {
                response.reason = "需要更新的记录不存在";
                return response;
            }
            request.body.u_update_time = DateTime.Now;
            DbFactory.dbFactory.Db.Updateable(request.body).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();

            response.result = "OK";
            return response;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse Delete(BaseDeleteRequest request)
        {
            BaseResponse response = new BaseResponse();
            response.reason = request.idList.Count.ToString();

            if (request.idList == null || request.idList.Count <= 0)
            {
                response.reason = "请传入需要删除数据的主键";
                return response;
            }
            DbFactory.dbFactory.Db.Deleteable<t_user>().In(request.idList).ExecuteCommand();
            response.result = "OK";
            return response;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [NotLoginFilter]
        [HttpPost]
        public BaseResponse<LoginInfo> Login(BaseRequest<t_user> request)
        {
            BaseResponse<LoginInfo> response = new BaseResponse<LoginInfo>();
            response.result = "NG";
            t_user user = dbFactory.Db.Queryable<t_user>().Select("*").First(a => a.u_name == request.body.u_name);
            if (user == null)
            {
                response.reason = "该用户不存在";
                return response;
            }
            if (user.u_state != 1)
            {
                response.reason = "该用户已被禁用或删除";
                return response;
            }
            if (user.u_pass_word != request.body.u_pass_word)
            {
                response.reason = "密码不正确";
                return response;
            }
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.RoleIdList = new List<int>();
            loginInfo.UserInfo = new User();
            loginInfo.UserInfo.u_id = user.u_id;
            if (user.u_last_login_time.HasValue)
                loginInfo.UserInfo.u_last_login_time = user.u_last_login_time.Value.ToString("yyyy-MM-dd HH:mm:ss");
            loginInfo.UserInfo.u_name = user.u_name;
            loginInfo.UserInfo.u_phone = user.u_phone;
            loginInfo.UserInfo.u_sex = user.u_sex;
            List<t_user_group> userGroupList = dbFactory.Db.Queryable<t_user_group>()
                .Select("*").Where(a => a.u_id == user.u_id).ToList();
            foreach (var ug in userGroupList)
            {
                t_group group = new t_group();
                Role role = new Role();
                group = dbFactory.Db.Queryable<t_group>().First(a => a.g_id == ug.g_id);
                if (group != null)
                {
                    loginInfo.RoleIdList.Add(group.g_id);
                }
            }
            string token = Guid.NewGuid().ToString();
            DbFactory.dbFactory.Db.Updateable<t_user>().SetColumns(a => new t_user() { u_token = token, u_last_login_time = DateTime.Now }).Where(a => a.u_id == user.u_id).ExecuteCommand();
            loginInfo.UserInfo.token = token;
            LogHelper.LogInfo(token);
            HttpContext.Current.Session.Add(token, loginInfo);
            HttpContext.Current.Session.Timeout = 40;
            response.Body = loginInfo;

            response.result = "OK";
            return response;
        }
        /// <summary>
        /// 登出
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public BaseResponse LoginOut(BaseRequest<t_user> request)
        {
            BaseResponse response = new BaseResponse();
            response.result = "NG";
            t_user user = dbFactory.Db.Queryable<t_user>().Select("*").Where(a => a.u_state == 1).First(a => a.u_name == request.body.u_name);
            if (user == null)
            {
                response.reason = "需要登出的用户不存在";
                return response;
            }
            if (user.u_token != null)
            {
                HttpContext.Current.Session.Remove(user.u_token);
                dbFactory.Db.Updateable<t_user>().SetColumns(a => a.u_token == "").Where(a => a.u_id == user.u_id).ExecuteCommand();
            }


            response.result = "OK";
            return response;
        }
    }
}